import { Children, cloneElement, isValidElement, useMemo } from 'react';

import { Divider, Dropdown } from 'antd';
import cs from 'classnames';

import { Icon } from '@iconify/react';

import styles from './index.module.scss';

export interface SpaceProps {
  children?: React.ReactNode;
  className?: string;
  /** 最多显示多少个功能,多余的下拉选择 */
  limit?: number;
}

const Space: React.FC<SpaceProps> = ({ children, className, limit = 4 }) => {
  const render = useMemo(() => {
    const listChildren = Children.toArray(children).filter(Boolean);

    if (typeof limit === 'number' && listChildren.length > limit) {
      const before = listChildren.slice(0, limit);
      const after = listChildren.slice(limit);

      return (
        <>
          {before.map((item, index) => {
            return (
              <div className={styles['space-item']} key={index}>
                {item}

                <Divider type="vertical" />
              </div>
            );
          })}

          <Dropdown
            menu={{
              items: after.map((item, index) => ({
                key: String(index),
                label: isValidElement(item)
                  ? cloneElement(item, {
                      // @ts-ignore
                      style: {
                        display: 'block'
                      }
                    })
                  : item
              }))
            }}
          >
            <Icon icon="ri:more-fill" className={styles['more']} />
          </Dropdown>
        </>
      );
    }

    return listChildren.map((item, index) => {
      return (
        <div className={styles['space-item']} key={index}>
          {index > 0 && <Divider type="vertical" />}

          {item}
        </div>
      );
    });
  }, [children, limit]);

  return <div className={cs(styles['space'], className)}>{render}</div>;
};

export default Space;
